package Top200;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * @author zhangmin
 * @create 2022-02-18 19:59
 */
public class fourSum18 {
    public List<List<Integer>> twoSum(int[] nums,int start,int target){
        int left=start,right=nums.length-1;
        List<List<Integer>> res=new LinkedList<>();
        while (left<right){
            int sum=nums[left]+nums[right];
            int l=nums[left],r=nums[right];
            if (sum==target){
                List<Integer> list=new LinkedList<>();
                list.add(l);list.add(r);
                res.add(list);
                while (left<right&&nums[left]==l){
                    left++;
                }
                while (left<right&&nums[right]==r){
                    right--;
                }
            }else if (sum<target){
                while (left<right&&nums[left]==l){
                    left++;
                }
            }else {
                while (left<right&&nums[right]==r){
                    right--;
                }
            }
        }
        return res;
    }

    public List<List<Integer>> nSum(int[] nums, int n, int start, int target){
        int nsize=nums.length;
        List<List<Integer>> res=new LinkedList<>();
        if (n==2){
            //调用两数之和
            return twoSum(nums,start,target);
        }else {
            //递归调用（n-1）数之和
            for (int i = start; i < nsize; i++) {
                List<List<Integer>> lists = nSum(nums, n - 1, i + 1, target - nums[i]);
                for (List<Integer> list:lists) {
                    list.add(nums[i]);
                    res.add(list);
                }
                while (i+1<nsize&&nums[i]==nums[i+1]) i++;
            }
        }
        return res;
    }
    public List<List<Integer>> fourSum(int[] nums, int target) {
        Arrays.sort(nums);
        return nSum(nums,4,0,target);
    }
}
